import requests
import json
import time

# 查询 IP 地址位置的函数
# "https://ipinfo.io/{ip_address}/json"替换成IP查询API
def query_ip_location(ip_address):
    url = f"https://ipinfo.io/{ip_address}/json"
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.json()
        else:
            return {"error": f"Failed to retrieve data for {ip_address}, status code: {response.status_code}"}
    except Exception as e:
        return {"error": f"Exception occurred for {ip_address}: {str(e)}"}

# 批量查询 IP 地址位置的函数
def batch_query_ip_location(ip_addresses):
    results = []
    for ip in ip_addresses:
        print(f"Querying location for IP: {ip}")
        location_info = query_ip_location(ip)
        results.append(location_info)
        time.sleep(1)  # 加一个短暂的延迟，避免频繁请求被限制
    return results

# 保存查询结果到文件
def save_results_to_file(results, filename):
    with open(filename, 'w') as f:
        json.dump(results, f, indent=4)
    print(f"Results saved to {filename}")

# 示例：批量查询的 IP 地址列表
ip_list = [
    "8.8.8.8",   # Google
    "1.1.1.1",   # Cloudflare
    "127.0.0.1"  # localhost
]

# 执行批量查询
results = batch_query_ip_location(ip_list)

# 打印结果
for result in results:
    print(result)

# 保存结果到文件
save_results_to_file(results, "ip_location_results.json")
